import {useMMKVObject} from '@/hooks/useMMkv';
import {useMemo, useState} from 'react';
import FastImageWithSkel from '../FastImageWithSkel';
import {TouchableOpacity, View, Text, ActivityIndicator} from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
import {useAppTheme, Icon} from 'tsun-smart-ui';
import {Image} from 'react-native';
import {type UserInfo} from '@/services/api/userApi';
import {useUpload} from '@/hooks/useUpload';
import toast from '@/utils/toast';
import {useTranslation} from 'react-i18next';

const Avatar = ({
  needUpload = true,
  className,
  uri,
  onChange,
}: {
  needUpload?: boolean;
  className?: string;
  uri?: string;
  onChange?: (uri: string) => void;
}) => {
  const {t} = useTranslation();
  const [userInfo] = useMMKVObject<UserInfo>('user_info');
  const defaultAvatar = useMemo(
    () =>
      Image.resolveAssetSource(
        userInfo?.userType === 1
          ? require('@/assets/imgs/avatar.png')
          : require('@/assets/imgs/avatar-installer.png'),
      ),
    [userInfo?.userType],
  );

  const {
    uploading: isUploading,
    progress: uploadProgress,
    startUpload,
  } = useUpload();
  const avatar = uri ? Image.resolveAssetSource({uri}) : defaultAvatar;
  const [isDownload, setIsDownload] = useState(false);
  const theme = useAppTheme();
  return (
    <View className={`rounded-full relative  ${className}  `}>
      <FastImageWithSkel
        onLoadEnd={() => {
          needUpload && setIsDownload(false);
        }}
        source={avatar}
        onError={() => {
          needUpload && setIsDownload(false);
        }}
        className="size-full rounded-full"
      />

      {/* 上传进度遮罩 */}
      {(isUploading || isDownload) && (
        <View className="absolute inset-0 bg-black/50 rounded-full flex items-center justify-center">
          <ActivityIndicator
            size="small"
            color={theme.colors?.brand?.onPrimary}
          />
          <Text className="text-white text-sm font-medium mt-2">
            {Math.round(uploadProgress)}%
          </Text>
        </View>
      )}

      {needUpload && (
        <TouchableOpacity
          style={{
            backgroundColor: theme.colors?.brand?.primaryLight,
            borderColor: theme.colors?.neutral?.white,
          }}
          className="absolute bottom-0 right-0 border-2 rounded-full"
          disabled={isUploading}
          onPress={() => {
            ImagePicker.openPicker({
              mediaType: 'photo',
              quality: 0.8,
              includeBase64: false,
              cropping: true,
              cropperCircleOverlay: true,
              cropperCancelText: t('user.logOutCancel'),
              cropperChooseText: t('dytable.submit'),
            })
              .then(async file => {
                startUpload({
                  name: file.filename!,
                  type: file.mime!,
                  uri: file.path!,
                })
                  .then(res => {
                    const imageUrl = res.data.originPath;
                    onChange?.(imageUrl);
                    setIsDownload(true);
                  })
                  .catch((e: Error) => {
                    toast.error({
                      message: e.message,
                    });
                  });
              })
              .catch(e => {
                if (e.message.includes('permission')) {
                  toast.error({
                    message: t('staticRoutes.noPower'),
                  });
                }else{
                  console.log(e);
                  
                }
              });
          }}>
          <Icon
            name="camera"
            color={
              isUploading
                ? theme.colors?.neutral?.secondaryTitle
                : theme.colors?.brand?.primary
            }
            size={32}
          />
        </TouchableOpacity>
      )}
    </View>
  );
};

export default Avatar;
